<template>
  <div class="orders-view">
    <Header />
    <AppHeader />
    <div class="orders-container">
      <div class="orders-header">
        <h2>
          <el-icon>
            <Document />
          </el-icon> 我的订单
        </h2>
      </div>
      <div class="orders-content">
        <el-skeleton :rows="5" animated :loading="loading && orderList.length === 0" />
        <div v-for="order in orderList" :key="order.orderId" class="order-card">
          <!-- 订单头部信息 -->
          <div class="order-header">
            <div class="order-info">
              <div class="order-id-section">
                <span class="order-id-label">订单编号：</span>
                <span class="order-id">{{ order.orderId }}</span>
                <el-button type="text" size="small" @click="copyOrderId(order.orderId)" class="copy-btn">
                  <el-icon>
                    <DocumentCopy />
                  </el-icon>
                </el-button>
              </div>
              <div class="order-time-section">
                <span class="order-time-label">创建时间：</span>
                <span class="order-time">{{ formatTime(order.createTime) }}</span>
              </div>
            </div>
            <div class="order-status-section">
              <el-tag :type="getStatusType(order.orderStatus)" effect="light" size="large">
                {{ getStatusText(order.orderStatus) }}
              </el-tag>
              <el-tag v-if="order.payStatus === 1" type="success" effect="light" size="large" class="ml-2">
                已支付
              </el-tag>
              <el-tag v-else type="warning" effect="light" size="large" class="ml-2">
                待支付
              </el-tag>
            </div>
          </div>
          <!-- 收货人信息 -->
          <div class="order-address" v-if="order.receiverName">
            <div class="address-info">
              <el-icon>
                <Location />
              </el-icon>
              <div class="receiver-info">
                <span class="receiver-name">{{ order.receiverName }}</span>
                <span class="receiver-phone">{{ formatPhone(order.receiverPhone) }}</span>
              </div>
              <div class="address-detail">
                {{ order.receiverProvince }} {{ order.receiverCity }} {{ order.receiverDistrict }} {{
                  order.receiverAddress }}
              </div>
            </div>
          </div>
          <!-- 商品列表 -->
          <div class="order-items">
            <div class="items-header">
              <h3>商品信息</h3>
            </div>
            <div
              v-for="item in (Array.isArray(order.orderDetails) ? order.orderDetails : parseOrderDetails(order.orderDetails))"
              :key="item.detailId" class="order-item">
              <div class="item-image">
                <img :src="item.productImg || '/src/assets/product-default.png'" :alt="item.productName" />
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-specification" v-if="item.specification">
                  <span class="spec-label">规格：</span>
                  <span class="spec-value">{{ item.specification }}</span>
                </div>
                <div class="item-price">¥{{ item.sellingPrice }}</div>
              </div>
              <div class="item-quantity">
                <span class="quantity-label">数量：</span>
                <span class="quantity-text">{{ item.quantity }}</span>
              </div>
              <div class="item-total">
                <span class="total-label">小计：</span>
                <span class="total-text">¥{{ item.subTotal }}</span>
              </div>
            </div>
          </div>
          <!-- 订单底部 -->
          <div class="order-footer">
            <div class="order-summary">
              <div class="order-total">
                <span class="total-label">订单总额：</span>
                <span class="total-amount">¥{{ order.orderTotal }}</span>
              </div>
              <div class="order-details">
                <span class="detail-item">商品数量：{{ getTotalItems(order.orderDetails) }} 件</span>
                <span class="detail-item">订单状态：{{ getStatusText(order.orderStatus) }}</span>
                <span class="detail-item">支付状态：{{ order.payStatus === 1 ? '已支付' : '待支付' }}</span>
              </div>
            </div>
            <div class="order-actions">
              <el-button v-if="order.payStatus === 0" type="primary" size="large" @click="handlePayment(order)"
                :loading="paymentLoading">
                <el-icon>
                  <Wallet />
                </el-icon>
                立即支付
              </el-button>
              <el-button v-if="order.orderStatus === 1" type="success" size="large"
                @click="handleConfirmReceive(order)">
                <el-icon>
                  <Check />
                </el-icon>
                确认收货
              </el-button>
              <el-button v-if="order.orderStatus === 0 && order.payStatus === 0" type="danger" size="large"
                @click="handleCancelOrder(order)">
                <el-icon>
                  <Close />
                </el-icon>
                取消订单
              </el-button>
              <el-button v-if="order.orderStatus === 2 || order.orderStatus === 3" type="danger" size="large"
                @click="handleDeleteOrder(order)">
                <el-icon>
                  <Delete />
                </el-icon>
                删除订单
              </el-button>
            </div>
          </div>
        </div>
        <div v-if="!loading && orderList.length === 0" class="empty-orders">
          <el-empty description="暂无订单" :image-size="200">
            <el-button type="primary" @click="$router.push('/')">去购物</el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Document, DocumentCopy, Location, Wallet, Check, Close, Delete, View } from '@element-plus/icons-vue';
import { getUserOrders, confirmReceive, deleteOrder, cancelOrder } from '@/api/order';

export default {
  name: 'OrdersView',
  components: {
    Document,
    DocumentCopy,
    Location,
    Wallet,
    Check,
    Close,
    Delete,
    View
  },
  data() {
    return {
      orderList: [],
      loading: false,
      paymentLoading: false,
      // 你可以根据需要添加其他变量
    };
  },
  mounted() {
    this.loadOrders();
  },
  methods: {
    async loadOrders() {
      this.loading = true;
      try {
        const user = JSON.parse(localStorage.getItem('user'));
        if (!user || !user.userId) {
          this.orderList = [];
          this.loading = false;
          return;
        }
        const res = await getUserOrders(user.userId);
        // 假设返回数据结构为 { data: { orders: [...] } }
        this.orderList = (res.data && res.data.orders) ? res.data.orders : [];
      } catch (e) {
        this.orderList = [];
      }
      this.loading = false;
    },
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      const h = String(date.getHours()).padStart(2, '0');
      const min = String(date.getMinutes()).padStart(2, '0');
      const s = String(date.getSeconds()).padStart(2, '0');
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },
    getStatusType(status) {
      // 0=待支付, 1=已发货, 2=已完成, 3=已取消
      switch (status) {
        case 0: return 'warning';   // 待支付
        case 1: return 'info';      // 已发货
        case 2: return 'success';   // 已完成
        case 3: return 'danger';    // 已取消
        default: return 'info';
      }
    },
    formatPhone(phone) {
      if (!phone) return '';
      // 例如：将 13812345678 格式化为 138****5678
      return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
    },
    parseOrderDetails(details) {
      if (!details) return [];
      if (Array.isArray(details)) return details;
      if (typeof details === 'string') {
        try {
          const arr = JSON.parse(details);
          return Array.isArray(arr) ? arr : [];
        } catch (e) {
          // 兼容后端返回的逗号分隔字符串（如SQL GROUP_CONCAT）
          if (details.includes('|')) {
            return details.split(',').map(str => {
              const parts = str.split('|');
              return {
                detailId: parts[0],
                productId: parts[1],
                productName: parts[2],
                productImg: parts[3],
                sellingPrice: Number(parts[4]),
                quantity: Number(parts[5]),
                subTotal: Number(parts[6]),
                specification: parts[7] || '默认规格'
              };
            });
          }
          return [];
        }
      }
      return [];
    },
    getTotalItems(details) {
      const items = this.parseOrderDetails(details);
      if (!Array.isArray(items)) return 0;
      return items.reduce((sum, item) => sum + (item.quantity || 0), 0);
    },
    getStatusText(status) {
      // 0=待支付, 1=已发货, 2=已完成, 3=已取消
      switch (status) {
        case 0: return '待支付';
        case 1: return '已发货';
        case 2: return '已完成';
        case 3: return '已取消';
        default: return '未知状态';
      }
    },
    async handleConfirmReceive(order) {
      try {
        await confirmReceive(order.orderId);
        if (this.$message) {
          this.$message.success('确认收货成功');
        } else {
          alert('确认收货成功');
        }
        this.loadOrders();
      } catch (e) {
        if (this.$message) {
          this.$message.error('确认收货失败');
        } else {
          alert('确认收货失败');
        }
      }
    },
    handleViewDetail(order) {
      // 这里可以根据实际需求跳转详情页或弹窗
      // 先简单弹窗显示订单详情
      if (this.$alert) {
        this.$alert(JSON.stringify(order, null, 2), '订单详情');
      } else {
        alert(JSON.stringify(order, null, 2));
      }
    },
    async handleDeleteOrder(order) {
      try {
        await deleteOrder(order.orderId);
        if (this.$message) {
          this.$message.success('订单删除成功');
        } else {
          alert('订单删除成功');
        }
        this.loadOrders();
      } catch (e) {
        if (this.$message) {
          this.$message.error('订单删除失败');
        } else {
          alert('订单删除失败');
        }
      }
    },
    async handleCancelOrder(order) {
      try {
        await cancelOrder(order.orderId);
        if (this.$message) {
          this.$message.success('订单取消成功');
        } else {
          alert('订单取消成功');
        }
        this.loadOrders();
      } catch (e) {
        if (this.$message) {
          this.$message.error('订单取消失败');
        } else {
          alert('订单取消失败');
        }
      }
    },
    handlePayment(order) {
      // 跳转到支付页面，假设有/payment/:orderId路由
      this.$router.push({ name: 'Payment', params: { orderId: order.orderId } });
    },
    // ...其他方法
  }
}
</script>

<style scoped>
.orders-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.orders-header h2 {
  font-size: 2rem;
  color: #333;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.orders-content {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
}

.order-card {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 2rem;
  transition: box-shadow 0.3s;
}

.order-card:hover {
  box-shadow: 0 8px 24px rgba(24, 144, 255, 0.15);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.2rem;
}

.order-id-section {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.copy-btn {
  margin-left: 8px;
}

.order-status-section {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.order-address {
  margin-bottom: 1rem;
  background: #f8fafc;
  border-radius: 6px;
  padding: 0.75rem 1rem;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.address-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.receiver-info {
  margin-left: 8px;
  font-weight: 500;
  color: #333;
}

.address-detail {
  margin-left: 16px;
  color: #888;
  font-size: 0.98rem;
}

.order-items {
  margin-bottom: 1rem;
}

.items-header {
  font-weight: bold;
  margin-bottom: 8px;
  color: #1890ff;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background: #f7faff;
  border-radius: 4px;
  padding: 0.5rem 1rem;
}

.item-image img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
  background: #f0f0f0;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: #333;
}

.item-specification {
  font-size: 0.95rem;
  color: #888;
}

.item-price {
  color: #fa541c;
  font-weight: bold;
  margin-top: 0.2rem;
}

.item-quantity,
.item-total {
  margin-left: 16px;
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1.2rem;
  border-top: 1px solid #f0f0f0;
  padding-top: 1rem;
}

.order-summary {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.order-total {
  font-size: 1.1em;
  font-weight: bold;
  color: #1890ff;
}

.order-details {
  color: #888;
  font-size: 0.95em;
  display: flex;
  gap: 1.5rem;
}

.order-actions {
  display: flex;
  gap: 0.5rem;
}

.order-actions .el-button {
  margin-left: 0;
  border-radius: 4px;
  font-weight: 500;
  transition: background 0.3s;
}

.order-actions .el-button:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.empty-orders {
  text-align: center;
  margin-top: 40px;
}

@media (max-width: 900px) {
  .orders-content {
    max-width: 100%;
    padding: 0 1rem;
  }

  .order-card {
    padding: 1rem;
  }
}

@media (max-width: 600px) {
  .orders-header h2 {
    font-size: 1.2rem;
  }

  .order-card {
    padding: 0.5rem;
  }

  .order-footer {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .order-details {
    flex-direction: column;
    gap: 0.5rem;
  }
}
</style>